import React, {
  createRef,
  memo,
  useCallback,
  useEffect,
  useState,
} from "react";
import { shallowEqual, useDispatch, useSelector } from "react-redux";
import { useNavigate } from "react-router-dom";
import { ThunkDispatch } from "@reduxjs/toolkit";
import { ExclamationCircleFilled } from "@ant-design/icons";
import { Table, Button, Modal, message, Form, Tree, Select } from "antd";

import {
  DeleteUserService,
  GetDepartmentService,
  GetMenuService,
  GetUserByIdService,
  UpdatedUserInfoService,
} from "@/service";

import UserModal from "./modal";
import useColums from "./config";
import UserWrapper from "./style";

import {
  fetchGetUserListThunk,
  IStore,
  fetchSearchUserListThunk,
  fetchMenuThunk,
  fetchUserDetail,
} from "@/store";

import CoderForm from "@/components/coder-form/coder-form";
const { confirm } = Modal;
const permission = [
  { value: 1, label: "查看" },
  { value: 2, label: "查看 添加" },
  { value: 3, label: "查看 添加 修改" },
  { value: 4, label: "查看 添加 修改 删除" },
];
const User = memo(() => {
  const userStore = useSelector((state: IStore) => state.user, shallowEqual);
  const dispatch = useDispatch<ThunkDispatch<any, any, any>>();
  const [dataSource, setDataSource] = useState<any[]>([]);
  useEffect(() => {
    GetMenuService().then((res) => {
      console.log("=> GetMenuService ", res)
      const data = res.data.list.map((item: any) => ({
        title: item.name,
        key: item.ID,
        children: item.children.length > 0 ? item.children.map((itemy: any) => ({
          title: itemy.name,
          key: itemy.ID,
        })) : [],
      }));
      setTreeData(data);
    });
    console.log("=> userStore", userStore);
  }, []);
  // 对话
  const initial = {
    title: "修改用户信息",
    edit: true,
  };
  const [currentModalData, setCurrentModalData] = useState(initial);
  const modalRef = createRef<{ showModal: (item?: any) => void }>();
  // 编辑显示
  function handleOpenModal(item: any, callback?: () => void) {
    modalRef.current?.showModal(item);
    callback && callback();
  }
  //  添加用户
  function addUser() {
    handleOpenModal({}, () => {
      setCurrentModalData({ title: "新增用户", edit: false });
    });
  }
  // 删除弹框
  const showConfirm = (item: any) => {
    confirm({
      title: "是否删除该用户?",
      icon: <ExclamationCircleFilled />,
      content: <strong>{item.user_name}</strong>,
      async onOk() {
        const res: any = await DeleteUserService(item.id);
        if (res.code === 0) {
          message.success(res.msg);
        } else {
          message.error(res.msg);
        }
        dispatch(fetchGetUserListThunk());
      },
      onCancel() {
        message.info("取消删除");
      },
    });
  };

  // 给函数调用
  const { columns, config } = useColums(
    handleOpenModal,
    showConfirm,
    () => {
      // 默认打开
      if (currentModalData.title != initial.title) {
        setCurrentModalData(initial);
      }
    },
    updateUserStatus,
    controlPermission,
    userStore.department.map((item) => ({
      label: item.name,
      value: item.name,
    })),
    userStore
  );
  function updateUserStatus(item: any, status: string) {
    let obj = {};
    if (status == "status") {
      obj = {
        ...item,
        status: item.status == "0" ? true : false,
      };
    } else if (status == "mail_is_allowed") {
      obj = {
        ...item,
        mail_is_allowed: item.mail_is_allowed == 0 ? 1 : 0,
      };
    } else {
      obj = {
        ...item,
        update_balance: !item.update_balance
      };
    }
    UpdatedUserInfoService(obj).then(() => {
      dispatch(fetchGetUserListThunk())
    });
  }
  // 打开菜单控制Modal
  async function controlPermission(item: any) {
    setPerData(item);
    setIsModalOpenPermission(true);
    const user: any = await GetUserByIdService(item.id);
    const menu = await GetMenuService(user.data.permissions);
    let checkedKey: any[] = [1, 2,];
    menu.data.list.forEach((item: any) => {
      item.children?.forEach((itemy: any) => {
        checkedKey.push(itemy.ID);
      });
    });
    const half = menu.data.list.map((item: any) => item.ID);
    setCheckedKeys([...new Set(checkedKey)]);
    setCheckedHelfKeys(half);
  }
  // 打开菜单控制Modal Flag
  const [isModalOpenPermission, setIsModalOpenPermission] = useState(false);
  // 打开菜单的Modal Data
  const [perData, setPerData] = useState<any>({});
  // Modal 里 树结构显示的数据
  const [treeData, setTreeData] = useState<any[]>([]);
  // Modal选中的树结构
  const [checkedKeys, setCheckedKeys] = useState<any[]>([1, 2,]);
  const [checkedHelfKeys, setCheckedHelfKeys] = useState<any[]>([]);
  // 确认修改的
  function handlerControlPermissionClick() {
    UpdatedUserInfoService({
      ...perData,
      permissions: [...new Set([...checkedHelfKeys, ...checkedKeys])].join(","),
    }).then(async (res: any) => {
      if (res.code == 0) {
        await message.success(res.msg);
        dispatch(fetchGetUserListThunk());
        setIsModalOpenPermission(false);
        const user: any = localStorage.getItem("user");
        if (user) {
          const _ = JSON.parse(user);
          if (user.id == perData.id) dispatch(fetchMenuThunk(perData.id));
        }
        return;
      }
      await message.error(res.msg);
    });
  }
  useEffect(() => {
    const dataSource = userStore.users?.map((item: any) => ({
      ...item,
      key: item.id,
    }));
    setDataSource(dataSource);
  }, [userStore.users]);
  // 表配置
  const [searchValue, setSearchValue] = useState({});
  async function handleSearchClick() {
    if (Object.keys(searchValue).length) {
      dispatch(fetchSearchUserListThunk(searchValue));
    }
  }
  function handleResetClick() {
    setSearchValue({});
    dispatch(fetchGetUserListThunk());
  }
  const memoHandleResetClick = useCallback(() => handleResetClick(), []);
  const memoSetValue = useCallback(
    (val: any) => setSearchValue(val),
    [searchValue]
  );
  const memoHandleSearchClick = useCallback(
    () => handleSearchClick(),
    [searchValue]
  );

  return (
    <UserWrapper>
      <div className="card user-header" style={{ paddingTop: "25px" }}>
        <CoderForm
          value={searchValue}
          setValue={memoSetValue}
          searchCallback={memoHandleSearchClick}
          resetCallback={memoHandleResetClick}
          config={config}
        >
          <Button type="primary" onClick={() => addUser()}>
            新增用户
          </Button>
        </CoderForm>
      </div>
      <div className="card user-table">
        <Table
          bordered
          scroll={{ x: 1450 }}
          pagination={{
            pageSizeOptions: [6, 12, 24, 48],
            defaultPageSize: 6,
          }}
          dataSource={dataSource}
          columns={columns}
        />
      </div>
      <Modal
        title="权限控制"
        open={isModalOpenPermission}
        onOk={() => handlerControlPermissionClick()}
        onCancel={() => {
          setIsModalOpenPermission(false);
        }}
        className="top-6"
      >
        <div className="max-h-[650px] overflow-y-auto">
          <div className="flex gap-3 mb-2">
            <div className="w-1/2">
              <span>按钮操作:</span>
              <Select
                className="w-full"
                value={permission[perData.rid - 1]}
                onChange={(value) => {
                  setPerData({ ...perData, rid: value });
                }}
                options={permission}
              />
            </div>
            <div className="w-1/2">
              <span>客户显示: </span>
              <Select
                className="w-full"
                value={perData.show_order_info}
                onChange={(value) => {
                  console.log("选择了", value);
                  setPerData({ ...perData, show_order_info: value });
                }}
                options={[
                  { value: false, label: "订单客户不显示" },
                  { value: true, label: "订单客户显示" },
                ]}
              />
            </div>
          </div>
          <Tree
            defaultExpandAll
            checkedKeys={{
              checked: checkedKeys,
              halfChecked: checkedHelfKeys,
            }}
            checkable
            onCheck={(checkedKeys, e) => {
              setCheckedKeys(checkedKeys as any[]);
              setCheckedHelfKeys(e.halfCheckedKeys as any[]);
            }}
            treeData={treeData}
          />
        </div>
      </Modal>
      <UserModal operate={currentModalData} ref={modalRef}></UserModal>
    </UserWrapper>
  );
});

export default User;
